<?php

namespace app\api\controller;

use think\Db;
use think\Controller;
class Ali extends Base
{
    protected $config = array(
        'partner' => '2088621781822784',
        'seller_id' => 'admin@bagepanzi.com',
        'sign_type' => 'RSA2',
        'it_b_pay' => '10m',
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlnemjJ0OSNt1SzGhSkdWtmK7S1FKSwpcRiCIfVF0ViP3ZAB8MlpFTdQ7Zq0mXbIRHU3V5HCsmJLtvuyws+QJY90BMGxlItKPXc+5ZnRqIJIaBd99qlCX/CNCZA4mmsocMmz/LT41QMv5SMB1PiBPJqQme/WiaBZlFcmCETU8e2n/YBlGj3GaDy5tWy9W6qHEUc/1H74LEDsQJn176rKCzEfAUwaZOv6eoElGzXfrgXmgvbXpuBvAY9TwQ0rK6YGMeO5fUM157Ti/4/cWIxVFUj06zi5aNgGNCrv6jxDZPG4l+sQeUay9xc4sClHI8YXw6jq6LJHdr8uif5BW6YhsqQIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwamELkZPcThxb5wg789OSjkkfbFcwlb8KavQ1TKdoa7ZR3w6QdzYLXkS/aqGgNjT0+WJm/yup+wzr7G/o7POY8PlUvaLofxOw/CiA8NLAki+hrmFZhfPUrV218u5cNKYaQx5PIbjpSxI/fwOPXIJ9ZV5LJUouA1EbGthrskiM/lbHHYonfwdr94b6I+e2HuiRMhvRgVI55a8tPMIdJvO+u4GQLLbtOlL0aZ+cOAKvz7T9eSMwvdzDs0IYRQgasKgyyVdvxOB0XaCfYPtQ8CC+CQs53b+EfX6A/WG+cgXYR75MVHzHWTP4Qg+EszEOxIfcrJkiBa4gd+Fs2wPp73HrQIDAQAB",
        'private_key' => 'MIIEpQIBAAKCAQEAlnemjJ0OSNt1SzGhSkdWtmK7S1FKSwpcRiCIfVF0ViP3ZAB8MlpFTdQ7Zq0mXbIRHU3V5HCsmJLtvuyws+QJY90BMGxlItKPXc+5ZnRqIJIaBd99qlCX/CNCZA4mmsocMmz/LT41QMv5SMB1PiBPJqQme/WiaBZlFcmCETU8e2n/YBlGj3GaDy5tWy9W6qHEUc/1H74LEDsQJn176rKCzEfAUwaZOv6eoElGzXfrgXmgvbXpuBvAY9TwQ0rK6YGMeO5fUM157Ti/4/cWIxVFUj06zi5aNgGNCrv6jxDZPG4l+sQeUay9xc4sClHI8YXw6jq6LJHdr8uif5BW6YhsqQIDAQABAoIBAH3+xynrwbBkhD1o26R1RDkJR8hz04AutsHKMECv2njfOSM1/Mm1KV9Ynj0GNKA0oXwmVzso1n4UWpyLWhPomaxTvdEskyuroX1umdMfHFcVwFC2qmXZgssRQ2DBMLZhE2duOedKthECPEYdUo+pQl4bCla2gz4hspeh2xZJu9Gi0ga3LHfPPFbm4P4V9yf60kAkr6CIHYJgK1j7ECfZmhj/FiS/MGk+X6ognPSTAAWaycDrCPfrTmMiYAScRZ8TOpTUW8AX+SIrnhVfEzRrw1qEc1Nhtd9aGY9SUfLQwwd6RB1wmzBSa4H55b316yjqUZGRBWvrE8/4Pl1vK8In5/kCgYEAx4NoUTyiWUVR/GdywThsW1FJ3j2Xz6OzFjMEkMuLOeAj88zk4cqalTBZzlNs/BLf40GmBTJuDooEfKNR7mjY2Cy8pfkr8Ez5r1RC8uU1y3+Dd2MXvSbwlu4l9LqAMD8XFuVSdSuezd1wh7/gDKuBz4JOEI4x0vUTGrmnIc4VcRMCgYEAwRFtSwzf+KsrdKbKGQqGRTVfZluwjirjZnXfco7VBj1ZoGBNcv5i7oS68FmAKUiA1SfZBlQxKMju4Uq73LOYfZ/z4irXCcd74mb7qpwi9/XmXEc/b09ZPoqfQNrGgMbw/jK+19cDqnR0jpmGbtneIMWmFAB3WVZXZXpxyjp0HtMCgYEAt6yEZvV5SNIGjmX2QWfeaZtGc/EkR6YfAvro4xxgCmIM9y/ULwJEmcAvjUFEfjQqJZ+UZghtRblONChvDxs7NpjI+8uO5eUXoI/kKpVVlwjHUSvK+PpWV7za+JiR1tjeOtfXt8L2qfOI25CLhV6HXTBLCfa+a8XvVpVABmEhYD0CgYEAisY++/omJzTKCJA2pic1ehuyFf4D+zyCtcw2L77RCiog+TEfmm+VpwKK6GY8w+/UguKgkXcE2t8LLa8tN6d0DaBiigfnB6V2u7bwYKLYU8lRqrSfuR+c82JqtBBNLJVS9jR9juGDRgttGG7r/VPm4UGQbcIkB3gTW+LWVdkMTHcCgYEArXyiBWXQN2yK9yK86/23GupMQ6jb6kGP0PjtMLBZ74W6n3GCQQ34Q9SzL4Ea2ZcWtHFoLmirjvQJAvq98lHCdbtUY62l7CT99PQxXw87+OEHeXWIeyhvLl9cIQtlS1E9HQydWIjGtpSGSE8FJG0TCWsYuzgTm3VmNbxE3CnTjWg='
    );
    public $body;
    public $subject;
    public $total_amount;
    public $out_trade_no;
    

    public function getParam($no, $money, $body, $subject,$NotifyUrl = "http://csdl.jintianjifen.cn/api/Ali/huidiao")
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
            $aop->appId = "2019052065205188";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl($NotifyUrl);
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
            $res['msg'] = $response;
            $res['status'] = 200;
            return $res;
        } catch(\Exception $e) {
            $res['msgsss'] = 'error';
            $res['status'] = 100;
            return $res;
        }
    }



    public function checkReturn($data)
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['public_key'];
        $flag = $aop->rsaCheckV1($data, NULL, "RSA2");
        if($flag) {
            return $data;
        } else {
            return false;
        }
    }
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }

    public function write_admin_log($data)
    {
        file_put_contents ( APP_PATH."api/controller/alipay_log.txt", date ( "Y-m-d H:i:s" ) . "  " . $data . "\r\n", FILE_APPEND );
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn(input());
        $this->write_admin_log("response: ".var_export($getInfo,true));
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                Db::startTrans ();
                try{
                    $num = $getInfo['out_trade_no'];
                    if($getInfo['body'] != 'payMoney'){
                        $info = Db::name('order')->where('o_order_num',$num)->find();
                    }
                    $red_rat = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
                    $b = new Base();
                    switch($getInfo['body']){
                        case 'balanceUp':
                            Db::name('shop')->where('shop_id',$info['o_shop_id'])->setInc ('shop_balance',$info['o_money']);
                            break;
                        case 'cashPledge':
                            $dai = Db::name('shop s')
                                ->join('admin a','s.shop_superior_agent = a.id','left')
                                ->where('shop_id',$info['o_shop_id'])
                                ->field('id,integral')
                                ->find();
                            Db::name('admin')->where('id',$dai['id'])->setDec ('integral',$info['o_jifen']);
                            Db::name('shop')->where('shop_id',$info['o_shop_id'])->setInc ('shop_integral',$info['o_jifen']);
                            Db::name('shop')->where('shop_id',$info['o_shop_id'])->setInc ('shop_pledge_money',$info['o_money']);
                            break;
                        case 'joinFund':
                            $fund_info = Db::name('fund')->where('fund_id',$info['o_fund_id'])->find();
                            Db::name('fund_join')->insert(['j_order_id'=>$info['o_id'],'j_fund_id'=>$info['o_fund_id'],'j_user_id'=>$info['o_user_id'],'j_pay'=>$info['o_money'],'j_pay_time'=>$getInfo['gmt_payment']]);
                            Db::name('fund')->where(['fund_id'=>$info['o_fund_id']])->inc ('fund_join')->inc('fund_money',$info['o_money'])->update ();
                            if(($fund_info['fund_money']+$info['o_money']) >= $fund_info['fund_plan']){
                                Db::name('fund')->where('fund_id',$info['o_fund_id'])->setField ('fund_status',5);
                                Db::name('fund_join')->where('j_fund_id',$info['o_fund_id'])->setField ('j_status',2);
                            }
                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'参与众筹','n_content'=>'您参与众筹支付'.$info['o_money'].'元','n_images'=>'','n_type'=>3,'n_user_id'=>$info['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                            try {
                                $b->jpushUser(1,$info['o_user_id'],'您参与众筹支付'.$info['o_money'].'元',json([]));
                            } catch (\Exception $e) {}
                            break;
                        case 'payOne':
                            Db::name('u_user')->where('user_id',$info['o_user_id'])->update (['user_one_pay'=>2,'user_edit_time'=>date('Y-m-d H:i:s')]);
                            break;
                        case 'payMoney':
                            $v = Db::name('order')->where(['o_order_num'=>['in',$num]])->field('SUM(o_money) AS o_money,SUM(o_jifen) AS o_jifen,o_user_id')->find();
                            $user = Db::name('u_user')->where('user_id',$v['o_user_id'])->find();
                            $rat = Db::name('jifen_conf')->where('conf_id',2)->value('conf_rate');
                            $nums = Db::name('order')->where(['o_order_num'=>['in',$num]])->select ();
                            foreach($nums as $key=>$vo){
                                $oi_goods_name = Db::name('order_info')->where('oi_order_id',$vo['o_id'])->column ('oi_goods_name');
                                if($vo['o_jifen'] > 0){
                                    $b->consume ($vo['o_user_id'] , $vo['o_jifen'] , $vo['o_shop_id']);
                                    Db::name('shop')->where('shop_id',$vo['o_shop_id'])->setInc ('shop_balance_yet',$vo['o_jifen']*$rat);
                                    Db::name('jifen_consume')->insert(['consume_content'=>'购买'.implode (',',$oi_goods_name).'商品订单消费'.$vo[ 'o_jifen' ].'积分','consume_user_id'=>$user['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                }

                                if($vo['o_money'] > 0){
//                                    $red_yajin_jian = $this->getRedYajinValue($vo['o_id'],$red_rat);
//                                    if($red_yajin_jian > $vo['o_money']){
//                                        $red_yajin_jian = $vo['o_money'];
//                                    }
                                    Db::name('shop')->where('shop_id',$vo['o_shop_id'])->setInc ('shop_balance_yet',$vo['o_money']);
                                }

                                $o_status = in_array ($vo['o_cate'],[1,3]) ? 2 : 10;
                                Db::name('order')->where('o_order_num',$vo['o_order_num'])->update(['o_status'=>$o_status,'o_pay_status'=>2, 'o_third_order_num' => $getInfo[ 'trade_no' ]]);
                                $dec = Db::name('order_info')->where('oi_order_id',$vo['o_id'])->find();
                                if($dec['oi_goods_model']){
                                    Db::name('product_model')->where('m_id',$dec['oi_goods_model'])->setDec ('m_num',$dec['oi_num']);
                                }else{
                                    Db::name('product')->where('p_id',$dec['oi_goods_id'])->setDec ('p_stock_num',$dec['oi_num']);
                                }
                                Db::name('product')->where('p_id',$dec['oi_goods_id'])->setInc ('p_sell_yet',$dec['oi_num']);
                                Db::name('notice')->insert (['n_to'=>2,'n_title'=>'订单消息','n_content'=>'您有新的订单！','n_images'=>'','n_type'=>2,'n_user_id'=>$vo['o_shop_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                $this->sayMyName($vo['o_shop_id'],0,0,$vo['o_order_num'],3);

                                Db::name('notice')->insert (['n_to'=>1,'n_title'=>'订单支付','n_content'=>'购买'.implode (',',$oi_goods_name).'商品订单支付成功，等待卖家处理','n_images'=>'','n_type'=>2,'n_user_id'=>$user['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                try {
                                    $b->jpushShop(1,$vo['o_shop_id'],'您有新的订单！',['type2' => 1024,'msg' => "您有一个新的线上订单"]);
                                    $b->jpushUser(1,$user['user_id'],'订单支付成功，等待卖家处理',json([]));
                                    $b->jpushDeviceShop($vo['o_shop_id'], '您有一个新的线上订单');
                                } catch (\Exception $e) {}
                            }
                            break;
                        case 'payMoneyOne':
                            $user = Db::name('u_user')->where('user_id',$info['o_user_id'])->find();
                            // $rat = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
                            $oi_goods_name = Db::name('order_info')->where('oi_order_id',$info['o_id'])->value ('oi_goods_name');
                            if($info['o_money'] > 0){
//                                $red_yajin_jian = $this->getRedYajinValue($info['o_id'],$red_rat);
//                                if($red_yajin_jian > $info['o_money']){
//                                    $red_yajin_jian = $info['o_money'];
//                                }
                                Db::name('shop')->where('shop_id',$info['o_shop_id'])->setInc ('shop_balance_yet',$info['o_money']-$info['o_m_money']);
                            }
                            $o_status = in_array ($info['o_cate'],[1,3]) ? 2 : 10;
                            Db::name('order')->where('o_order_num',$info['o_order_num'])->update(['o_status'=>$o_status,'o_pay_status'=>2, 'o_third_order_num' => $getInfo[ 'trade_no' ]]);
                            $dec = Db::name('order_info')->where('oi_order_id',$info['o_id'])->find();
                            if($dec['oi_goods_model']){
                                //不是id......
//                            Db::name('product_model')->where('m_id',$dec['oi_goods_model'])->setDec ('m_num',$dec['oi_num']);
                            }else{
                                Db::name('product')->where('p_id',$dec['oi_goods_id'])->setDec ('p_stock_num',$dec['oi_num']);
                            }
                            Db::name('product')->where('p_id',$dec['oi_goods_id'])->setInc ('p_sell_yet',$dec['oi_num']);

                            //-----------------------------分佣 start -----------------------------------------
                            $one_good = Db::name('product')->where('p_id',$dec['oi_goods_id'])->find ();
                            $one_fen = [];
                            $one_fen[] = [
                                'record_order_number' => $info['o_order_num'],
                                'record_user_id' => $info['o_user_id'],
                                'record_from_type' => 1,
                                'record_payment_type' => $info['o_pay_type'],
                                'record_status' => 1,
//                            'record_get_type' => 2,
                                'record_jifen' => $one_good['p_give'],
                                'record_money' => 0,
                                'record_add_time' => date('Y-m-d H:i:s'),
                            ];
                            $one_fen[] = [
                                'record_order_number' => $info['o_order_num'],
                                'record_user_id' => 0,
                                'record_from_type' => 5,
                                'record_payment_type' => $info['o_pay_type'],
                                'record_status' => 1,
//                            'record_get_type' => 1,
                                'record_jifen' => 0,
                                'record_money' => $one_good['p_m_single_system'],
                                'record_add_time' => date('Y-m-d H:i:s'),
                            ];
                            if($info['o_m_user_id'] > 0){
                                $one_fen[] = [
                                    'record_order_number' => $info['o_order_num'],
                                    'record_user_id' => $info['o_m_user_id'],
                                    'record_from_type' => 3,
                                    'record_payment_type' => $info['o_pay_type'],
                                    'record_status' => 1,
//                                    'record_get_type' => 1,
                                    'record_jifen' => $one_good['p_m_single_one_jifen'],
                                    'record_money' => $one_good['p_m_single_one_money'],
                                    'record_add_time' => date('Y-m-d H:i:s'),
                                ];
                                if($user['user_recommend']){
                                    $recommendLevel = Db::name('u_user')->where('user_id',$user['user_recommend'])->value('user_level');
                                    if($recommendLevel && $recommendLevel > 1){
                                        $one_fen[] = [
                                            'record_order_number' => $info['o_order_num'],
                                            'record_user_id' => $user['user_recommend'],
                                            'record_from_type' => 4,
                                            'record_payment_type' => $info['o_pay_type'],
                                            'record_status' => 1,
//                                        'record_get_type' => 1,
                                            'record_jifen' => 0,
                                            'record_money' => $one_good['p_m_single_two'],
                                            'record_add_time' => date('Y-m-d H:i:s'),
                                        ];
                                    }else{
                                        $one_fen[] = [
                                            'record_order_number' => $info['o_order_num'],
                                            'record_user_id' => 0,
                                            'record_from_type' => 6,
                                            'record_payment_type' => $info['o_pay_type'],
                                            'record_status' => 1,
//                                        'record_get_type' => 1,
                                            'record_jifen' => 0,
                                            'record_money' => $one_good['p_m_single_two'],
                                            'record_add_time' => date('Y-m-d H:i:s'),
                                        ];
                                    }
                                }else{
                                    $one_fen[] = [
                                        'record_order_number' => $info['o_order_num'],
                                        'record_user_id' => 0,
                                        'record_from_type' => 6,
                                        'record_payment_type' => $info['o_pay_type'],
                                        'record_status' => 1,
//                                    'record_get_type' => 1,
                                        'record_jifen' => 0,
                                        'record_money' => $one_good['p_m_single_two'],
                                        'record_add_time' => date('Y-m-d H:i:s'),
                                    ];
                                }
                            }else{
                                $one_fen[] = [
                                    'record_order_number' => $info['o_order_num'],
                                    'record_user_id' => 0,
                                    'record_from_type' => 6,
                                    'record_payment_type' => $info['o_pay_type'],
                                    'record_status' => 1,
//                                'record_get_type' => 1,
                                    'record_jifen' => 0,
                                    'record_money' => $one_good['p_m_single_all_money'] - $one_good['p_m_single_system'],
                                    'record_add_time' => date('Y-m-d H:i:s'),
                                ];
                            }
                            Db::name('m_record')->insertAll($one_fen);
                            //-----------------------------分佣 end  ------------------------------------------

                            Db::name('notice')->insert (['n_to'=>2,'n_title'=>'订单消息','n_content'=>'您有新的订单！','n_images'=>'','n_type'=>2,'n_user_id'=>$info['o_shop_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                            try{
                                $this->sayMyName($info['o_shop_id'],0,0,$info['o_order_num'],3);
                                $b->jpushShop(1,$info['o_shop_id'],'您有新的订单！',['type2' => 1024,'msg' => "您有一个新的线上订单"]);
                            }catch (\Exception $e){}


                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'订单支付','n_content'=>'购买'.$oi_goods_name.'商品订单支付成功，等待卖家处理','n_images'=>'','n_type'=>2,'n_user_id'=>$user['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                            try{
                                $b->jpushUser(1,$user['user_id'],'订单支付成功，等待卖家处理',json([]));

                                $b->jpushDeviceShop($info['o_shop_id'], '您有一个新的线上订单');
                            }catch (\Exception $e){}

                            if($info['o_m_user_id'] > 0){
                                Db::name('notice')->insert (['n_to'=>1,'n_title'=>'订单支付','n_content'=>'用户购买您的小店'.$oi_goods_name.'商品订单支付成功，确认收货后佣金到账','n_images'=>'','n_type'=>2,'n_user_id'=>$info['o_m_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                try{
                                    $b->jpushUser(1,$info['o_m_user_id'],'您的小店订单支付成功，确认收货后佣金到账',json([]));
                                }catch (\Exception $e){}
                            }

                            break;
                        case 'payMoneyTeam':
                            $info = Db::name('m_order')->where('mo_order_num', $num)->find();
                            $one_good = Db::name('product')->where('p_id', $info['mo_p_id'])->find();
                            $oi_goods_name = $info['mo_goods_name'];
                            $haveUsersData = Db::name('m_order')
                                ->where('mo_status', 1)
                                ->where('mo_pay_status', 2)
                                ->where('mo_store_uid', $info['mo_store_uid'])
                                ->where('mo_p_id', $info['mo_p_id'])
                                ->select();
                            $haveUsersData[] = $info;
                            $haveUsers = count($haveUsersData);
                            $o_status = in_array($info['mo_cate'], [1, 3]) ? 2 : 10;
                            $mo_update = [
                                'mo_pay_status' => 2,
                                'mo_pay_money' => $getInfo['total_amount'],
                                'mo_third_order_num' => $getInfo['trade_no'],
                                'mo_team_money' => $one_good['p_m_team_all_money'],
                                'mo_o_status' => $o_status,
                                'mo_status' => 1,
                            ];
                            if ($info['mo_store_uid']) {
                                $leftData = Db::name('m_goods')
                                    ->where('good_p_id', $info['mo_p_id'])
                                    ->where('good_user_id', $info['mo_store_uid'])
                                    ->field('good_team_count,good_team_status')
                                    ->find();
                                $left = $leftData['good_team_count'];
                                $reatart_status = $leftData['good_team_status'];
                                $mo_update['mo_team_count'] = $info['mo_p_id'] . $info['mo_store_uid'] . $left;
                            } else {
                                $mo_update['mo_team_count'] = $info['mo_p_id'] . 0 . $one_good['p_m_team_count'];
                                $reatart_status = $one_good['p_m_team_can_status'];
                            }
                            //-------------------------------------------------------------------------------------------
                            Db::name('notice')->insert(['n_to' => 1, 'n_title' => '订单支付', 'n_content' => '购买' . $oi_goods_name . '商品订单参团成功，等待开奖', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $info['mo_user_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                            try {
                                $b->jpushUser(1, $info['mo_user_id'], '订单支付成功，您已成功参团，等待开奖', json([]));
                            } catch (\Exception $e) {
                            }
                            //-------------------------------------------------------------------------------------------
                            if ($haveUsers == $one_good['p_m_team_nums']) { //开奖啦
                                //1、先把自己的改为已开奖
                                $mo_update['mo_status'] = 2;
                                //2、再把其他的改为已开奖(挪到第4一起了)
                                //3、期数加1，更改开始的状态和时间
                                if ($info['mo_store_uid']) {
                                    Db::name('m_goods')
                                        ->where('good_p_id', $info['mo_p_id'])
                                        ->where('good_user_id', $info['mo_store_uid'])
                                        ->inc('good_team_count')
                                        ->update(['good_team_status' => 1]);
                                } else {
                                    Db::name('product')->where('p_id', $info['mo_p_id'])
                                        ->inc('p_m_team_count')
                                        ->update(['p_m_team_can_status' => 1]);
                                }
                                //4、开奖(先找出所有的，再排除中过的，最后统一改)
                                $joinUsers = Db::name('m_order')
                                    ->where('mo_pay_status', 2)
                                    ->where('mo_store_uid', $info['mo_store_uid'])
                                    ->where('mo_p_id', $info['mo_p_id'])
                                    ->where('mo_team_count', $mo_update['mo_team_count'])
                                    ->column('mo_user_id');
                                $joinUsers[] = $info['mo_user_id'];
                                $todayPriceUser = Db::name('m_order')
                                    ->where('mo_get_user_id', '>', 0)
                                    ->whereTime('mo_time', 'today')
                                    ->group('mo_get_user_id')
                                    ->column('mo_get_user_id');
                                $lastUsers = array_diff($joinUsers, $todayPriceUser);
                                if (empty($lastUsers)) {
                                    $lastUsers = $joinUsers;
                                }
                                $randUser = rand(0, count($lastUsers) - 1);
                                $get_user_id = $lastUsers[$randUser];
                                $mo_update['mo_get_user_id'] = $get_user_id;
                                Db::name('m_order')
                                    ->where('mo_pay_status', 2)
                                    ->where('mo_store_uid', $info['mo_store_uid'])
                                    ->where('mo_p_id', $info['mo_p_id'])
                                    ->where('mo_team_count', $mo_update['mo_team_count'])
                                    ->update(['mo_status' => 2, 'mo_get_user_id' => $get_user_id, 'mo_team_money' => $one_good['p_m_team_all_money']]);
                                if($get_user_id == $info['mo_user_id']){
                                    $getOrderUser = $info;
                                    $getOrderUser['mo_third_order_num'] = $getInfo['trade_no'];
                                    $getOrderUser['mo_team_money'] = $one_good['p_m_team_all_money'];
                                }else{
                                    $getOrderUser = Db::name('m_order')
                                        ->where('mo_store_uid', $info['mo_store_uid'])
                                        ->where('mo_p_id', $info['mo_p_id'])
                                        ->where('mo_team_count', $mo_update['mo_team_count'])
                                        ->where('mo_user_id', $get_user_id)
                                        ->order('mo_time desc')
                                        ->find();
                                }
                                //5、入订单表：
                                $j_param1 = [
                                    'o_type' => 2,
                                    'o_user_id' => $get_user_id,
                                    'o_order_num' => $getOrderUser['mo_order_num'],
                                    'o_third_order_num' => $getOrderUser['mo_third_order_num'],
                                    'o_money' => $getOrderUser['mo_money'],
                                    'o_m_money' => $getOrderUser['mo_team_money'],
                                    'o_status' => $o_status,
                                    'o_pay_type' => $getOrderUser['mo_pay_type'],
                                    'o_pay_status' => 2,
                                    'o_shop_id' => $getOrderUser['mo_shop_id'],
                                    'o_shop_name' => $getOrderUser['mo_shop_name'],
                                    'o_cate' => $getOrderUser['mo_cate'],
                                    'o_postage' => $getOrderUser['mo_postage'],
                                    'o_qrcode' => $getOrderUser['mo_qrcode'],
                                    'o_name' => $getOrderUser['mo_name'],
                                    'o_phone' => $getOrderUser['mo_phone'],
                                    'o_address' => $getOrderUser['mo_address'],
                                    'o_m_type' => 3,
                                    'o_m_user_id' => $getOrderUser['mo_store_uid'],
                                    'o_m_team_uids' => ',' . implode($joinUsers, ',') . ',',
                                    'o_add_time' => $getOrderUser['mo_time'],
                                ];
                                $j_get_id1 = Db::name('order')->insertGetId($j_param1);
                                $j_info_param1 = [
                                    'oi_order_id' => $j_get_id1,
                                    'oi_goods_id' => $getOrderUser['mo_p_id'],
                                    'oi_goods_name' => $getOrderUser['mo_goods_name'],
                                    'oi_goods_image' => $getOrderUser['mo_goods_image'],
                                    'oi_goods_price' => $getOrderUser['mo_goods_price'],
                                    'oi_goods_model' => $getOrderUser['mo_goods_model'], //规格名字
                                    'oi_num' => 1,
                                    'oi_total_price' => $getOrderUser['mo_goods_price'],
                                    'oi_total_jifen' => 0
                                ];
                                Db::name('order_info')->insert($j_info_param1);
                                //6、分佣：
                                //-----------------------------分佣 start -----------------------------------------
                                $today = date('Y-m-d H:i:s');
                                $one_fen = [];
                                $one_fen[] = [
                                    'record_order_number' => $getOrderUser['mo_order_num'],
                                    'record_user_id' => 0,
                                    'record_from_type' => 5,
                                    'record_payment_type' => $getOrderUser['mo_pay_type'],
                                    'record_status' => 2,
//                                'record_get_type' => 1,
                                    'record_jifen' => 0,
                                    'record_money' => $one_good['p_m_team_system'],
                                    'record_add_time' => $today,
                                    'record_sure_time' => $today,
                                    'record_type' => 2
                                ];
                                $one_fen[] = [
                                    'record_order_number' => $getOrderUser['mo_order_num'],
                                    'record_user_id' => $get_user_id,
                                    'record_from_type' => 8,
                                    'record_payment_type' => $getOrderUser['mo_pay_type'],
                                    'record_status' => 2,
//                                'record_get_type' => 1,
                                    'record_jifen' => $one_good['p_m_team_join_jifen'],
                                    'record_money' => $one_good['p_m_team_join_money'],
                                    'record_add_time' => $today,
                                    'record_sure_time' => $today,
                                    'record_type' => 2
                                ];
                                $captain_pay_type = 0;
                                foreach ($haveUsersData as $k => $v) {
                                    if ($v['mo_user_id'] == $info['mo_store_uid']) {
                                        $captain_pay_type = $v['mo_pay_type'];
                                    }
                                    $now_v = [
                                        'record_order_number' => $getOrderUser['mo_order_num'],
                                        'record_user_id' => $v['mo_user_id'],
                                        'record_from_type' => 8,
                                        'record_payment_type' => $v['mo_pay_type'],
                                        'record_status' => 2,
//                                    'record_get_type' => 1,
                                        'record_jifen' => 0,
                                        'record_money' => $one_good['p_m_team_join_money'],
                                        'record_add_time' => $today,
                                        'record_sure_time' => $today,
                                        'record_type' => 2
                                    ];
                                    if ($v['mo_user_id'] == $get_user_id) {
                                        $now_v['record_from_type'] = 2;
//                                    $now_v['record_get_type'] = 2;
                                        $now_v['record_jifen'] = $one_good['p_give'];
                                        $now_v['record_money'] = 0;
                                        $one_fen[] = $now_v;
                                        Db::name('win_info')->insert(['w_info'=>'恭喜拼中'.$oi_goods_name.'商品','w_user_id'=>$get_user_id,'w_type'=>2,'w_add_time'=>date('Y-m-d H:i:s')]);
                                        Db::name('notice')->insert(['n_to' => 1, 'n_title' => '团团赚开奖', 'n_content' => '购买' . $oi_goods_name . '商品订单参团已开奖，恭喜您，中奖了!并获得推广奖励¥'.$one_good['p_m_team_join_money'].'元，'.$one_good['p_m_team_join_jifen'].'积分', 'n_images' => '', 'n_type' => 5, 'n_user_id' => $v['mo_user_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                                        try {
                                            $b->jpushUser(1, $get_user_id, '团团赚已开奖，恭喜您中奖~', json([]));
                                        } catch (\Exception $e) {
                                        }
                                    } else {
//                                    $now_v['record_get_type'] = 2;
                                        $now_v['record_jifen'] = $one_good['p_m_team_join_jifen'];
                                        $one_fen[] = $now_v;

                                        Db::name('notice')->insert(['n_to' => 1, 'n_title' => '团团赚开奖', 'n_content' => '购买' . $oi_goods_name . '商品订单参团已开奖，您未中奖，支付金额将原路返回，并获得推广奖励¥'.$now_v['record_money'].'元，'.$now_v['record_jifen'].'积分', 'n_images' => '', 'n_type' => 5, 'n_user_id' => $v['mo_user_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                                        try {
                                            $b->jpushUser(1, $v['mo_user_id'], '团团赚已开奖，您未中奖~', json([]));
                                        } catch (\Exception $e) {
                                        }
                                    }
                                }
                                if ($info['mo_store_uid']) {
                                    $one_fen[] = [
                                        'record_order_number' => $getOrderUser['mo_order_num'],
                                        'record_user_id' => $info['mo_store_uid'],
                                        'record_from_type' => 7,
                                        'record_payment_type' => $captain_pay_type,
                                        'record_status' => 2,
//                                    'record_get_type' => 1,
                                        'record_jifen' => $one_good['p_m_team_leader_jifen'],
                                        'record_money' => $one_good['p_m_team_leader_money'],
                                        'record_add_time' => $today,
                                        'record_sure_time' => $today,
                                        'record_type' => 2
                                    ];
                                } else {
                                    $one_fen[] = [
                                        'record_order_number' => $getOrderUser['mo_order_num'],
                                        'record_user_id' => 0,
                                        'record_from_type' => 6,
                                        'record_payment_type' => 0,
                                        'record_status' => 2,
//                                    'record_get_type' => 1,
                                        'record_jifen' => $one_good['p_m_team_leader_jifen'],
                                        'record_money' => $one_good['p_m_team_leader_money'],
                                        'record_add_time' => $today,
                                        'record_sure_time' => $today,
                                        'record_type' => 2
                                    ];
                                }
                                //立即到账
                                if ($getOrderUser['mo_store_uid'] && $getOrderUser['mo_store_uid'] > 0) {
                                    $qu = Db::name('u_user')->where('user_id',$getOrderUser['mo_store_uid'])->value('user_area');
                                }else{
                                    $qu = Db::name('shop')->where('shop_id',$getOrderUser['mo_shop_id'])->value('shop_qu_id');
                                }
                                $quname = Db::name('area')->where('district_id', $qu)->value('district');
                                $cc = [
                                    '3' => '用户购买' . $one_good['p_name'] . '商品返佣',
                                    '4' => '用户购买' . $one_good['p_name'] . '商品返佣',
                                    '7' => $one_good['p_name'] . '商品团团赚团长奖励',
                                    '8' => $one_good['p_name'] . '商品参与团团赚奖励',
                                ];
                                foreach ($one_fen as $fen_k => $fen_v) {
                                    if(in_array($fen_v['record_from_type'],[3,4,7,8])) {
                                        if ($fen_v['record_money'] > 0) {
                                            Db::name('u_user')->where('user_id', $fen_v['record_user_id'])->setInc('user_m_pool_money', $fen_v['record_money']);
                                        }
                                        if ($fen_v['record_jifen'] > 0) {
                                            $this->jifenFlow($fen_v['record_jifen'], $qu, $fen_v['record_user_id'], 'poolFenYong');
                                            Db::name('jifen_consume')->insert(['consume_content' => $cc[$fen_v['record_from_type']] . $fen_v['record_jifen'] . "积分({$quname})", 'consume_user_id' => $fen_v['record_user_id'], 'consume_add_time' => date('Y-m-d H:i:s')]);
                                        }
                                        //推送待定
//                                    Db::name('jifen_consume')->insert(['consume_content'=>'购买产品池'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','consume_user_id'=>$order['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
//                                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购买商品','n_content'=>'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
//                                    $this->jpushUser(1,$order['o_user_id'],'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分',json([]));
                                    }
                                }
                                Db::name('m_record')->insertAll($one_fen);
                                //-----------------------------分佣 end  ------------------------------------------
                                //6、其他设置
//                                if(!$one_good['p_give']) $one_good['p_give'] = 0;
//                                $red_yajin_jian = $one_good['p_give'] * $red_rat;
                                Db::name('shop')->where('shop_id', $info['mo_shop_id'])->setInc('shop_balance_yet', $getOrderUser['mo_money']-$getOrderUser['mo_team_money']);
                                Db::name('notice')->insert(['n_to' => 2, 'n_title' => '订单消息', 'n_content' => '您有新的订单！', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $info['mo_shop_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                                try {
                                    $this->sayMyName($info['mo_shop_id'],0,0,$info['mo_order_num'],3);
                                    $b->jpushShop(1, $info['mo_shop_id'], '您有新的订单！', ['type2' => 1024, 'msg' => "您有一个新的线上订单"]);
                                } catch (\Exception $e) {
                                }

                            } else {
                                //如果是第一个付款的，重启状态和时间
                                if ($info['mo_store_uid']) {
                                    if ($reatart_status == 1) {
                                        Db::name('m_goods')
                                            ->where('good_p_id', $info['mo_p_id'])
                                            ->where('good_user_id', $info['mo_store_uid'])
                                            ->update([
                                                'good_team_status' => 2,
                                                'good_team_start_time' => date('Y-m-d H:i:s'),
                                                'good_team_end_time' => date('Y-m-d H:i:s', strtotime("+{$one_good['p_m_team_hours']} hours"))
                                            ]);
                                        Db::name('notice')->insert(['n_to' => 1, 'n_title' => '开团消息', 'n_content' => '您小店的'.$oi_goods_name . '商品已开团，请知悉', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $info['mo_store_uid'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                                        try {
                                            $b->jpushUser(1, $info['mo_store_uid'], '您小店的'.$oi_goods_name . '商品已开团', json([]));
                                        } catch (\Exception $e) {
                                        }
                                    }

                                } else {
                                    if ($reatart_status == 1) {
                                        Db::name('product')->where('p_id', $info['mo_p_id'])
                                            ->update([
                                                'p_m_team_can_status' => 2,
                                                'p_m_team_can_starttime' => date('Y-m-d H:i:s'),
                                                'p_m_team_can_endtime' => date('Y-m-d H:i:s', strtotime("+{$one_good['p_m_team_hours']} hours"))
                                            ]);
                                    }
                                }
                            }
//

                            Db::name('m_order')->where('mo_order_num', $info['mo_order_num'])->update($mo_update);
                            if ($info['mo_goods_model']) {
                                //不是id......
//                            Db::name('product_model')->where('m_id',$info['mo_goods_model'])->setDec ('m_num',1);
                            } else {
                                Db::name('product')->where('p_id', $info['mo_p_id'])->setDec('p_stock_num', 1);
                            }
                            Db::name('product')->where('p_id', $info['mo_p_id'])->setInc('p_sell_yet', 1);
                            break;
                        // 合伙人
                        case 'upPartner':
                            if ($info['o_pay_status'] != 2) {
                                // 付款成功添加合伙人信息
                                $temp['par_user_id'] = $info['o_user_id'];
                                $par_user_info  = DB::name('u_user')
                                                ->where(['user_id'=>$info['o_user_id']])
                                                ->field('user_username,user_phone,user_area,user_recommend')
                                                ->find();
                                $temp['par_user_username']  = $par_user_info['user_username'];
                                $temp['par_user_phone']     = $par_user_info['user_phone'];
                                $temp['par_qu_id']          = $par_user_info['user_area'];
                                $temp['par_add_time']       = date('Y-m-d H:i:s',time());
                                $temp['par_class_id']       = $info['o_class_id'];
                                $partner_class = DB::name('partner_class')
                                                ->where(['class_id'=>$info['o_class_id']])
                                                ->field('class_level,class_name,class_jifen,class_tui_jifen,class_agent_money,class_head_money,class_tui_money,class_fans_days')
                                                ->find();
                                $temp['par_class_level'] = $partner_class['class_level'];
                                // 如果是城市合伙人，需要后台代理商绑定
                                if ($partner_class['class_level'] != 3) {
                                    $temp['par_status'] = 2;
                                }else{
                                    $temp['par_status'] = 1;
                                }
                                // 是否是推荐人推荐
                                if (!empty($par_user_info['user_recommend'])) {
                                    $par_parent_id = DB::name('partner')
                                                    ->where(['par_user_id'=>$par_user_info['user_recommend'],'par_cancel'=>0])
                                                    ->value('par_id');
                                    if (!empty($par_parent_id)) {
                                        $temp['par_parent_id'] = $par_parent_id;
                                    }
                                }
                                // 升级合伙人
                                if ($info['o_partner_up'] == 1) {
                                    $old = DB::name('partner')
                                        ->where(['par_user_id'=>$info['o_user_id'],'par_cancel'=>0])
                                        ->find();
                                    $old_id = $old['par_id'];
                                    //往前推时间，减去已使用时间
                                    $date1 = date("Y-m-d",strtotime ($old['par_add_time']));
                                    $date2 = date ("Y-m-d");
                                    $diff = (strtotime ($date2) - strtotime($date1)) / (60 * 60 * 24);
                                    
                                    // 剩余粉丝天数计算
                                    $oldFansDays = DB::name('partner_class')->where(['class_id'=>$old['par_class_id']])->value('class_fans_days');
                                    $newFansDays = $partner_class['class_fans_days'];
                                    if ($diff > $oldFansDays) {
                                        $diff = $newFansDays - $oldFansDays;
                                        $temp['par_add_time'] = date("Y-m-d H:i:s",strtotime("+{$diff} day",strtotime ($temp['par_add_time'])));
                                    } else {
                                        // 还是原来的日期
                                        $temp['par_add_time'] = $old['par_add_time'];
                                    }

                                    $old_partner    = DB::name('partner')
                                                    ->where(['par_user_id'=>$info['o_user_id'],'par_cancel'=>0])
                                                    ->update(['par_cancel'=>1]);
                                    if (!empty($old_partner)) {
                                        $temp['par_up'] = 1;
                                    }
                                }
                                $temp['par_cancel'] = 0;
                                $partner_add = DB::name('partner')->insertGetId($temp);
                                // 判断合伙人的区代理是否存在，不存在积分由琅琊区1134出
                                $is_qu = DB::name('admin')->where('area',$temp['par_qu_id'])->find();
                                if (empty($is_qu)) {
                                    $temp['par_qu_id'] = 1134;
                                }
                                if (!empty($partner_add)) {
                                    // 修改用户表用户等级/付款方式
                                    if ($temp['par_class_level'] == 1) {
                                        $user_level = 4;
                                    }elseif ($temp['par_class_level'] == 2) {
                                        $user_level = 3;
                                    }
                                    // 修改用户信息
                                    if (!empty($user_level)) {
                                        DB::name('u_user')->where(['user_id'=>$info['o_user_id']])->update(['user_level'=>$user_level,'user_partner_type'=>$info['o_pay_type']]);
                                    }
                                    // 如果是升级用户，修改所有的该用直接下级的par_parent_id
                                    if ($info['o_partner_up'] == 1) {
                                        DB::name('partner')->where(['par_parent_id'=>$old_id])->update(['par_parent_id'=>$partner_add]);
                                    }
                                    // 付款成功奖励积分
                                    $integral = $info['o_money'];// 奖励用户支付钱的积分数
                                    Db::name('admin')->where('area',$temp['par_qu_id'])->setDec('integral',$integral);//代理送出积分
                                    $this->jifenFlow($integral,$temp['par_qu_id'],$info['o_user_id'],"partner");
                                    Db::name('jifen_consume')->insert(['consume_content'=>'您升级为'.$partner_class['class_name'].'获得'.$integral.'积分','consume_user_id'=>$info['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'成为合伙人','n_content'=>'您升级为'.$partner_class['class_name'].'支付金额'.$info['o_money'].'元','n_images'=>'','n_type'=>3,'n_user_id'=>$info['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                    try {
                                        $this->jpushUser(1,$info['o_user_id'],'您升级为'.$partner_class['class_name'].'支付金额'.$info['o_money'].'元',json([]));
                                    } catch (\Exception $e) {}
                                    // 推荐人奖励
                                    if (!empty($temp['par_parent_id'])) {
                                        $parent_partner = DB::name('partner')
                                                        ->where(['par_id'=>$temp['par_parent_id']])
                                                        ->find();
                                        // 判断合伙人的区代理是否存在，不存在积分由琅琊区1134出
                                        $is_parent_qu = DB::name('admin')->where('area',$parent_partner['par_qu_id'])->find();
                                        if (empty($is_qu)) {
                                            $parent_partner['par_qu_id'] = 1134;
                                        }
                                        // 如果是升级合伙人，推荐人奖励要减掉原来的推荐奖励
                                        if ($info['o_partner_up'] == 1) {
                                            $form_tui = DB::name('partner_invite')
                                                        ->where(['inv_be_userid'=>$info['o_user_id'],'inv_type'=>2,'inv_level'=>1,'inv_user_id'=>$parent_partner['par_user_id']])
                                                        ->field('inv_id,inv_integral,inv_money')
                                                        ->select();
                                            $form_jifen = 0;
                                            $form_money = 0;
                                            foreach ($form_tui as $key => $vo) {
                                                $form_jifen += $vo['inv_integral'];
                                                $form_money += $vo['inv_money'];
                                            }
                                            $partner_class['class_tui_jifen'] = $partner_class['class_tui_jifen'] - $form_jifen;
                                        }
                                        // 积分奖励
                                        Db::name('admin')->where('area',$parent_partner['par_qu_id'])->setDec('integral',$partner_class['class_tui_jifen']);//代理送出积分
                                        $this->jifenFlow($partner_class['class_tui_jifen'],$parent_partner['par_qu_id'],$parent_partner['par_user_id'],"parentPartner");
                                        // 邀请合伙人获得的积分奖励
                                        DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_par_integral',$partner_class['class_tui_jifen']);
                                        // 添加获得积分奖励记录
                                        $arr = [
                                                'inv_user_id'   => $parent_partner['par_user_id'],
                                                'inv_par_id'    => $parent_partner['par_id'],
                                                'inv_integral'  => $partner_class['class_tui_jifen'],
                                                'inv_level'     => 1,
                                                'inv_type'      => 2,
                                                'inv_be_userid' => $info['o_user_id'],
                                                'inv_add_time'  => date('Y-m-d H:i:s',time())
                                        ];
                                        DB::name('partner_invite')->insert($arr);
                                        $str1 = '';
                                        // 事业合伙人送推荐人现金
                                        if (!empty($partner_class['class_tui_money'])) {
                                            // 如果是升级合伙人，推荐人奖励要减掉原来的推荐奖励
                                            if ($info['o_partner_up'] == 1) {
                                                $partner_class['class_tui_money'] = $partner_class['class_tui_money'] - $form_money;
                                            }
                                            // 增加现金提现额度
                                            DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_money_balance',$partner_class['class_tui_money']);
                                            // 记录现金收益
                                            $arr = [
                                                'inv_user_id'   => $parent_partner['par_user_id'],
                                                'inv_par_id'    => $parent_partner['par_id'],
                                                'inv_money'     => $partner_class['class_tui_money'],
                                                'inv_level'     => 1,
                                                'inv_type'      => 2,
                                                'inv_be_userid' => $info['o_user_id'],
                                                'inv_add_time'  => date('Y-m-d H:i:s',time())
                                            ];
                                            DB::name('partner_invite')->insert($arr);
                                            // 邀请合伙人获得的现金奖励
                                            DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_par_money',$partner_class['class_tui_money']);
                                            $str1 = $partner_class['class_tui_money'].'元+';
                                        }
                                        Db::name('jifen_consume')->insert(['consume_content'=>'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励','consume_user_id'=>$parent_partner['par_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'推荐合伙人','n_content'=>'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励','n_images'=>'','n_type'=>3,'n_user_id'=>$parent_partner['par_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                        // $this->jpushUser(1,$parent_partner['par_user_id'],'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励',json([]));
                                    }
                                    // 升级合伙人代理商和总部的收益要减去之前的收益
                                    $area_money = DB::name('earnings')
                                                ->where(['m_area_user'=>$info['o_user_id'],'m_area_type'=>2,'m_area'=>$temp['par_qu_id']])
                                                ->sum('m_money');
                                    $head_money = DB::name('earnings')
                                                ->where(['m_area_user'=>$info['o_user_id'],'m_area_type'=>1,'m_area'=>1])
                                                ->sum('m_money');
                                    if (!empty($area_money)) {
                                        $partner_class['class_agent_money'] = $partner_class['class_agent_money'] - $area_money;
                                    }
                                    if (!empty($head_money)) {
                                        $partner_class['class_head_money'] = $partner_class['class_head_money'] - $head_money;
                                    }
                                    // 代理商获得奖励没有代理就总部拿
                                    if (!empty($is_qu)) {
                                        DB::name('admin')->where(['area'=>$temp['par_qu_id']])->setInc('balance',$partner_class['class_agent_money']);
                                    }else{
                                        DB::name('admin')->where('id',1)->setInc('balance',$partner_class['class_agent_money']);
                                    }
                                    // 记录现金收益
                                    Db::name('earnings')->insert(['m_money'=>$partner_class['class_agent_money'],'m_area'=>$temp['par_qu_id'],'m_add_time'=>date('Y-m-d H:i:s'),'m_area_type'=>2,'m_area_user'=>$temp['par_user_id']]);
                                    // 总部获得奖励
                                    DB::name('admin')->where('id',1)->setInc('balance',$partner_class['class_head_money']);
                                    // 记录现金收益
                                    Db::name('earnings')->insert(['m_money'=>$partner_class['class_head_money'],'m_area'=>1,'m_add_time'=>date('Y-m-d H:i:s'),'m_area_type'=>1,'m_area_user'=>$temp['par_user_id']]);
                                }
                            }
                        break;
                    }
                    if ($getInfo['body'] == 'upPartner') {
                        if ($info['o_pay_status'] != 2) {
                            Db::name('admin')->where('id',1)->setInc ('balance',$getInfo['total_amount']/100 );
                        }
                    }else{
                        if($getInfo['body'] != 'payMoneyOne' && $getInfo['body'] != 'payMoneyTeam') {
                            Db::name('admin')->where('id', 1)->setInc('balance', $getInfo['total_amount'] / 100);
                        }
                    }
                    if($getInfo['body'] != 'payMoney' && $getInfo['body'] != 'payMoneyOne' && $getInfo['body'] != 'payMoneyTeam') {
                        Db::name ('order')->where ('o_order_num' , $num)->update (['o_pay_status' => 2 , 'o_third_order_num' => $getInfo['trade_no']]);
                    }
                    Db::commit ();
                    return 'success';
                }catch(\Exception $e){
                    Db::rollback ();
                    return 'error';
                }
            }
        }
    }


    public function huidiao1(){
        $getInfo = $this->checkReturn(input());
        $this->write_admin_log("response: ".var_export($getInfo,true));
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                Db::startTrans ();
                try{
                    $num = $getInfo['out_trade_no'];
                    $money = $getInfo['total_amount'];
                    $record = Db::name('record')->where(['record_number'=>$num])->find();
                    $shop = Db::name('shop')->where(['shop_id'=>$record['record_shop_id']])->find();
                    $rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');
                    $b = new Base();
                    $money = $record['record_money'];
                    $yajin = 0;
                    if($record['record_give_jifen'] > 0){
                        $yajin = $record['record_give_jifen']*$rate;
//                        Db::name('shop')->where(['shop_id'=>$record['record_shop_id']])->dec('shop_integral',$record['record_give_jifen'])->dec('shop_pledge_money',$record['record_give_jifen']*$rate)->update();
                        $b->jifenFlow($record['record_give_jifen'],$shop['shop_qu_id'],$record['record_user_id'],"QRcodePay");
//                        Db::name('jifen_consume')->insert(['consume_content'=>'扫码支付给“'.$shop['shop_name'].'”赠送'.$record['record_give_jifen'].'积分','consume_user_id'=>$record['record_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                        Db::name('order')->insert(['o_type'=>5,'o_order_num'=>$this->getOrderNumber (),'o_money'=>$record['record_give_jifen']*$rate,'o_jifen'=>'','o_status'=>5,'o_pay_status'=>2,'o_shop_id'=>$record['record_shop_id'],'o_add_time'=>date('Y-m-d H:i:s')]);
                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'扫码支付','n_content'=>'扫码支付赠送'.$record['record_give_jifen'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$record['record_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                        try{
                            Db::name('admin')->where('area',$shop['shop_qu_id'])->setDec('integral',$record['record_give_jifen']);
                            $b->jpushUser(1,$record['record_user_id'],'扫码支付赠送'.$record['record_give_jifen'].'积分',json([]));
                            $b->jpushShop(1,$record['record_shop_id'],"收款{$money}元",['type'=>1,'money'=>$money,'type2' => 1024,'msg' => "支分宝到账{$money}元，送出{$record['record_give_jifen']}积分"]);
                        }catch (\Exception $e){

                        }
                    }else{
						try{
                            $b->jpushShop(1,$record['record_shop_id'],"收款{$money}元",['type'=>1,'money'=>$money,'type2' => 1024,'msg' => "支分宝到账{$money}元，没有送出积分"]);
                        }catch (\Exception $e){

                        }
						
					}
                    Db::name('jifen_consume')
                        ->insert ([
                            'consume_content'=>'扫码支付给“'.$shop['shop_name'].'”'.$money.'元，赠送'.$record['record_give_jifen'].'积分',
                            'consume_user_id'=>$record['record_user_id'],
                            'consume_add_time'=>date("Y-m-d H:i:s")
                        ]);
                    Db::name('record')
                        ->where(['record_id'=>$record['record_id']])
                        ->update([
                            'record_third_number' => $getInfo['trade_no'],
                            'record_status'=>2,
                            'record_pay_time'=>$getInfo['gmt_payment'],
                            'record_shop_balance'=>$shop['shop_balance']+$money-$yajin
                        ]);
                    Db::name('shop')
                        ->where('shop_id',$shop['shop_id'])
                        ->inc ('shop_balance',$money-$yajin)->inc('shop_all_balance',$money-$yajin)->update();
                    // 店铺现金成交额
                    Db::name('shop')
                        ->where('shop_id',$shop['shop_id'])
                        ->setInc('shop_money_balance',$money-$yajin);
                    // 店铺当日现金交易额// 定时任务，每日0点清空
                    DB::name('shop')->where('shop_id',$shop['shop_id'])->setInc ('shop_today_balance',$money-$yajin);
                    // 店铺现金交易1‰分红
                    $shop_user_id   = DB::name('shop')
                                    ->where('shop_id',$shop['shop_id'])
                                    ->value('shop_user_id');
                    $this->shop_profit($shop['shop_id'],$shop_user_id,$money,3);
                    //-----------------------红包改状态---------------------
                    if($record['record_ru_id'] > 0){
                        Db::name('m_red_user')
                            ->where('ru_id',$record['record_ru_id'])
                            ->update([
                                'ru_status' => 2
                            ]);
                    }
                    Db::commit ();
                    //------------------------语音设备播报-----------------
                    try{
                        $this->sayMyName($record['record_shop_id'],$money,$record['record_give_jifen'],$num);
                    }catch (\Exception $e){}
                    return 'success';
                }catch(\Exception $e){
                    Db::rollback ();
                    return 'error';
                }
            }
        }
    }
    public function huidiaored(){
        $getInfo = $this->checkReturn(input());
        $this->write_admin_log("response: ".var_export($getInfo,true));
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                Db::startTrans ();
                try{
                    $num = $getInfo['out_trade_no'];
                    Db::name('m_red')
                        ->where(['red_number'=>$num])
                        ->update([
                            'red_status'=>2
                        ]);
                    Db::commit ();
                    return 'success';
                }catch(\Exception $e){
                    Db::rollback ();
                    return 'error';
                }
            }
        }
    }


    public function refund($trade_no,$refund_amount){

        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest', EXTEND_PATH);
        $out_request_no = '';
        $refund_reason = '';
        $out_trade_no = '';

        $aop = new \AopClient;
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = "2019052065205188";
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = $this->config['public_key'];

        $bizContentarr= [
            'trade_no'=>$trade_no,
            'refund_amount'=>$refund_amount,
            'refund_reason'=>$refund_reason,
            'out_request_no'=>$out_request_no,
            'out_trade_no'=>$out_trade_no
        ];
        $biz_content = json_encode($bizContentarr,JSON_UNESCAPED_UNICODE);
        $request = new \AlipayTradeRefundRequest();
        $request->setBizContent ( $biz_content );
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            return ['status'=>200,'msg'=>$result->$responseNode];
        }else{
            return ['status'=>100,'msg'=>$result->$responseNode->sub_msg];
        }
    }



    public function tixianAgreeShopOrWork($number,$money,$phone,$name,$remark='')
    {
        header("Content-type:text/html;charset=UTF-8");
		$money = round($money,2);
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayFundTransToaccountTransferRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2019052065205188';
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey = $this->config['public_key'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayFundTransToaccountTransferRequest;
        $request->setBizContent("{" .
            "\"out_biz_no\":\"".$number."\"," .
            "\"payee_type\":\"ALIPAY_LOGONID\"," .
            "\"payee_account\":\"".$phone."\"," .
            "\"amount\":\"".$money."\"," .
            "\"payer_show_name\":\"支分宝转账\"," .
            "\"payee_real_name\":\"".$name."\"," .
            "\"remark\":\"".$remark."\"" .
            "}");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if($resultCode == 10000){
            return ['status'=>200,'msg'=>$result->$responseNode->order_id];
        }else if($resultCode == 40004) {
            return ['status'=>100,'msg'=>'账号或姓名错误'.$money];
        }else{
            return ['status'=>100,'msg'=>'操作失败'];
        }
    }
}